package com.shuqi.activity;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.shuqi.activity.viewport.SearchPopupWindow;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.Urls;
import com.shuqi.common.WebkitUrlDealer;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.ToastUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.BookSearchResultController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.SearchHistoryDao;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.SearchAssociateInfo;
import com.shuqi.sdk.ad.ADView;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 搜索结果页
 * 
 * @author linyuren
 * 
 */
public class BookSearchResultActivity extends ActivityBase implements OnClickListener,
        IEventListener {

    private String Tag = "BookSearchResultActivity";

    private final static int init = EventTypeConstants.BASE;
    private final static int initDataHotSuccess = init + 1;
    /** 客户端与网页交互的JS对象名 */
    private final String searchResultJsName = "anSQForWebJS_SERP";

    /** 搜索联想弹出框 */
    private SearchPopupWindow searchPopupWindow;

    /** 搜索联想控制器 */
    private BookSearchResultController controller;

    /** 搜索结果页web */
    private WebView searchResultWeb;

    /** 搜索关键字 从搜索界面传递过来的 */
    private String keyWord = "";

    /** 搜索联想词 */
    private String searchKeyWord = "";

    /** 存储搜索联想返回到额数据 */
    private List<SearchAssociateInfo> onlineList;

    private boolean isSetEditTextString = false;

    /** 输入框 */
    private EditText edit_searchbox = null;
    /** 清除文字按钮 */
    private View clear_search_content;

    private RelativeLayout toptitle;

    private LinearLayout includeError;

    private LinearLayout mIncludeLoading;

    private WebkitUrlDealer urlDealer;

    /** 隐藏键盘所用控件 */
    private View superView;

    /** 弹出搜索框的黑色半透明背景 */
    private View mSearchBackground;

    private ADView myADView;

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case init:
                    activityLogicForward();
                    break;
                case initDataHotSuccess:
                    activityInitData();
                    break;
                default:
                    break;
            }
        };
    };



    @Override
    public void onCreate(Bundle savedInstanceState) {
        this.controller =
                (BookSearchResultController) MainController.getMainManagerInstance()
                        .createController(MainController.CONTROLLER_ID_BOOKSEARCHRESULT, this);
        this.controller.addEventListener(this);
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.act_booksearchresult);
        urlDealer = new WebkitUrlDealer(this);
        StatisticsUtils.onEvent(this, StatisticsEventID.BOOKSEARCH_RESULT);
        handler.sendEmptyMessage(init);
    }

    private void search() {
        String keyword = edit_searchbox.getText().toString();
        if (keyword != null && keyword.trim().length() != 0) {
            Util.inputMethodControl(BookSearchResultActivity.this, false);

            if (this.searchPopupWindow != null) {
                this.searchPopupWindow.closePW();
            }
            SearchHistoryDao.getInstance().saveSearchHistory(keyword); // 保存到数据库
            StatisticsUtils.onEvent(this, StatisticsEventID.BOOKSEARCH_RESULT_INPUTKEYWORD);
            if (!Util.isNetworkConnected(this)) {
                return;
            } else {
                mRefreshWebView();
            }
        } else {
            ToastUtil.showToastFullyCustomizable(this, "请输入关键字");
            return;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.search_magnifyng:
                search();
                break;
            case R.id.bt_clear_searchbar:
                edit_searchbox.setText("");
                break;
            case R.id.retry:
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {
                    @Override
                    public void netErrorCallback() {
                        if (!Util.isNetworkConnected(BookSearchResultActivity.this)) {
                            return;
                        }
                        mRefreshWebView();
                    }
                });
                break;
        }
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:// 读取数据 写处理逻辑
                this.onlineList = (List<SearchAssociateInfo>) data;
                handler.sendEmptyMessage(initDataHotSuccess);
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (myADView != null) {
            myADView.onDestroy();
        }
        controller.onDestroy();
        super.onDestroy();
    }

    /**
     * 搜索联想或历史重新加载网页
     * */
    public void refreshLoadUrl(String searchContent) {
        this.isSetEditTextString = true;
        if (searchContent == null || "".equals(searchContent)) {
            showMsg("请填搜索词..");
        } else {
            Util.inputMethodControl(BookSearchResultActivity.this, false);
            this.searchResultWeb.loadUrl(urlDealer.dealUrl(new StringBuilder(50).append(Urls
                    .getWebSearchResultForAppJS(this, searchContent))));
            if (!TextUtils.isEmpty(searchContent)) {
                SearchHistoryDao.getInstance().saveSearchHistory(searchContent); // 保存到数据库
            }
        }
        this.edit_searchbox.setText(searchContent);
        this.edit_searchbox.setSelection(searchContent.trim().length());
        if (this.searchPopupWindow != null) {
            this.searchPopupWindow.closePW();
        }
        this.isSetEditTextString = false;
    }

    /**
     * 是否显示搜索框背景
     * 
     * @param isShow
     * */
    public void mShowSearchBackGround(boolean isShow) {
        if (isShow) {
            this.mSearchBackground.setVisibility(View.VISIBLE);
        } else {
            this.mSearchBackground.setVisibility(View.GONE);
        }
    }

    private OnEditorActionListener editorListener = new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                search();
                return true;
            }
            return false;
        }
    };

    /** 初始化广告 */
    private void initAds() {
        // 广告
        myADView =
                new ADView(this, 0, R.id.ads, 4, Urls.getAdvertisingURL(this, 4),
                        String.valueOf(Util.getVersionCode(this)), -1);// 非测试情况一定赋值为-1
        myADView.initADIDAdapter();// 一定要初始化广告id
        myADView.checkIsAdShown(false);
    }

    /** 初始化 */
    private void init() {
        keyWord = getIntent().getStringExtra("keyword");
        ((ImageView) this.findViewById(R.id.btn_back)).setOnClickListener(this);
        findViewById(R.id.search_magnifyng).setOnClickListener(this);
        clear_search_content = (View) findViewById(R.id.clear_search_content);
        findViewById(R.id.bt_clear_searchbar).setOnClickListener(this);
        superView = (View) findViewById(R.id.superView);
        superView.setOnTouchListener(new ItemTouchEvent());

        searchPopupWindow = new SearchPopupWindow(this);

        mSearchBackground = (View) findViewById(R.id.search_background);

        edit_searchbox = (EditText) findViewById(R.id.edit_searchbox);
        edit_searchbox.setText(keyWord);

        edit_searchbox.setOnEditorActionListener(editorListener);

        clear_search_content.setVisibility(View.VISIBLE);
        // edit_searchbox.setSelection(keyWord.trim().length());

        edit_searchbox.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log4an.e(Tag, "点击编辑框。。。");
                if (TextUtils.isEmpty(edit_searchbox.getText().toString())) {
                    edit_searchbox.setText("");
                    searchPopupWindow
                            .showJudgePW(BookSearchResultActivity.this, "", toptitle, null);
                } else {
                    searchKeyWord = edit_searchbox.getText().toString();
                    controller.handle(0, edit_searchbox.getText().toString());
                }
            }
        });

        edit_searchbox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log4an.e(Tag, "beforeTextChanged：" + s);
            }

            @Override
            public void afterTextChanged(Editable s) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                Log4an.e(Tag, "onTextChanged：" + s);

                if (TextUtils.isEmpty(s)) {
                    clear_search_content.setVisibility(View.GONE);
                    /** 弹出搜索历史 */
                    searchPopupWindow.showJudgePW(BookSearchResultActivity.this, s.toString(),
                            toptitle, null);
                } else {
                    clear_search_content.setVisibility(View.VISIBLE);
                    if (!isSetEditTextString) {
                        searchKeyWord = s.toString();
                        controller.handle(0, s.toString());
                    }
                }
            }
        });
    }

    /** 初始化webview */
    private void initWebView() {
        this.toptitle = (RelativeLayout) findViewById(R.id.toptitle);

        includeError = (LinearLayout) findViewById(R.id.include_error);
        mIncludeLoading = (LinearLayout) findViewById(R.id.include_loading);

        findViewById(R.id.retry).setOnClickListener(this);

        this.searchResultWeb = (WebView) this.findViewById(R.id.search_result_webview);
        this.searchResultWeb.getSettings().setJavaScriptEnabled(true);
        this.searchResultWeb.getSettings().setDomStorageEnabled(true);


        // 添加与网页的js交互功能
        this.searchResultWeb.addJavascriptInterface(new JavascriptInterface(this),
                this.searchResultJsName);

        this.searchResultWeb.getSettings().setSupportZoom(true);
        this.searchResultWeb.getSettings().setBuiltInZoomControls(true);

        this.searchResultWeb.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (TextUtils.isEmpty(url)) {
                    return true;
                }
                if (url.startsWith("http")) {
                    view.loadUrl(urlDealer.dealUrl(new StringBuilder(50).append(url)));
                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log4an.e(Tag, "onPageStarted");
                mIncludeLoading.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log4an.e(Tag, "onPageFinished");
                mIncludeLoading.setVisibility(View.GONE);
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description,
                    String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Log4an.e(Tag, "onReceivedError" + errorCode);
                searchResultWeb.setVisibility(View.GONE);
                includeError.setVisibility(View.VISIBLE);
            }
        });

        // 屏蔽复制
        this.searchResultWeb.setOnLongClickListener(new WebView.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        mRefreshWebView();
    }

    /** 重试loadurl */
    private void mRefreshWebView() {
        includeError.setVisibility(View.GONE);
        String keyword = edit_searchbox.getText().toString();
        searchResultWeb.loadUrl(urlDealer.dealUrl(new StringBuilder(50).append(Urls
                .getWebSearchResultForAppJS(this, keyword))));
        searchResultWeb.setVisibility(View.VISIBLE);
    }

    @Override
    public void activityLogicForward() {
        this.init();
        this.initWebView();
        initAds();
    }

    @Override
    public void activityInitData() {
        /** 弹出联想框 */
        this.searchPopupWindow.showJudgePW(BookSearchResultActivity.this, this.searchKeyWord,
                toptitle, this.onlineList);
    }

    /**
     * JS通信接口
     */
    public class JavascriptInterface {

        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }

        /** 跳转内置浏览器 */
        public void openUrlByAppWebkit(String url) {
            WebKitActivity.openWebkit(BookSearchResultActivity.this, url);
            StatisticsUtils.onEvent(context, StatisticsEventID.WEBKIT_WEBKIT_CORVER);
        }

        /** 跳转跳APP封面页 */
        public void openAppBookCover(String bookId) {
            BookCoverActivity.openBookCover(BookSearchResultActivity.this, bookId);
            StatisticsUtils.onEvent(context, StatisticsEventID.WEBKIT_WEBKIT_APP_CORVER);
        }
    }

    /** 隐藏键盘监听事件 */
    private class ItemTouchEvent implements OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_MOVE) {

            } else if (event.getAction() == MotionEvent.ACTION_UP) {

            } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
                Util.inputMethodControl(BookSearchResultActivity.this, false);
            }
            return false;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 打开搜索结果页
     * 
     * @param activity
     * @param keyWord
     */
    public static void open(Activity activity, String keyWord) {
        Intent intent = new Intent(activity, BookSearchResultActivity.class);
        intent.putExtra("keyword", keyWord);
        ActivityManager.getInstance().startNextActivity(intent, activity);
    }

}
